import React from 'react'
import './Upload.scss'


interface IProps {
    children?: React.ReactNode,
    accept?: string,
    multiple?: boolean,
    onChange?: (files: File[],fileList: FileList) => void,
}

export default function Upload(props: IProps) {
    const { children = <></>, accept='*', multiple=false, onChange=() => {},} = props;
    const inputRef = React.useRef<HTMLInputElement>(null);
    const boxRef = React.useRef<HTMLDivElement>(null);
    React.useEffect(() => {
        boxRef.current?.addEventListener('click', () => {
            inputRef.current?.click();
        });
        inputRef.current?.addEventListener('change', (e: Event) => {
            const target = e.target as HTMLInputElement;
            const fileList = target.files;
            const files: File[] = Array.from(fileList || []);
            if (fileList) {
                onChange(files,fileList);
            }
        });
    }, [])

    return (
        <div ref={boxRef} component-name='upload'>
            <input ref={inputRef} type='file' accept={accept} multiple={multiple} className='upload-input' />
            {children}
        </div>
    )
}
